package com.bjmashibing.system.huawei.service;

import com.bjmashibing.system.huawei.*;
import com.bjmashibing.system.huawei.buf_recv.Cbuffer_machine;
import com.bjmashibing.system.huawei.buf_recv.buf_machine;
import com.bjmashibing.system.huawei.domain.DataInfo;
import com.bjmashibing.system.huawei.domain.Token;
import com.bjmashibing.system.huawei.jdbc.SpringJdbcTemplate;
import com.bjmashibing.system.huawei.oppo.oppo_push;
import com.bjmashibing.system.huawei.vivo.Messaging;
import com.bjmashibing.system.huawei.vivo.vivo_push;
import com.bjmashibing.system.huawei.vivo.xiaomi_push;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Supplier;

/**
 * @Classname TaskService
 * @Description TODO
 * @Date 2021/5/4/004 11:01
 * @Created by Administrator
 */
@Service
public class TaskService {
    private final static Logger logger = LoggerFactory.getLogger(TaskService.class);
    public static Selector selector = null;
    public static ServerSocketChannel serverChannel_accept = null;
    public static volatile boolean started;
//    ExecutorService executor = Executors.newFixedThreadPool(2);

    public static int nums_static = 0;
    public static void ServerSocketChannel_init(int port) {
        try{

            selector = Selector.open();
            logger.info("selector.isOpen=" + selector.isOpen());
            //打开监听通道
            serverChannel_accept = ServerSocketChannel.open();
            //如果为 true，则此通道将被置于阻塞模式；如果为 false，则此通道将被置于非阻塞模式
            if ((serverChannel_accept.isOpen()) && (selector.isOpen())) {
                serverChannel_accept.configureBlocking(false);//开启非阻塞模式
                //绑定端口 backlog设为1024
                serverChannel_accept.socket().bind(new InetSocketAddress(port),1024);
                //监听客户端连接请求
                serverChannel_accept.register(selector, SelectionKey.OP_ACCEPT);
                //标记服务器已开启
                started = true;
                logger.info("服务器已启动，端口号：" + port);
            }


//            logger.info("socketChannel_data=" + socketChannel_data);
//            logger.info("selector=" + selector);
//            logger.info("serverChannel_accept=" + serverChannel_accept);
        }catch(IOException e){
            logger.info("ServerHandle,error=",e);
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void close_all() {
        try {
            logger.info("close_all...");
            stop();

//            int size = static_var.map_socket.size();
            for(SocketChannel value : static_var.map_socket.values()){
//                System.out.println(value);
                if (value != null) {
                    value.socket().close();
                    value.close();
                    value = null;
                }
            }

            if ((serverChannel_accept.isOpen()) && (selector.isOpen()) && (selector != null)) {
                if(selector.isOpen()){
                    selector.close();
                    selector = null;
                }
            }
            if ((serverChannel_accept.isOpen()) && (serverChannel_accept != null)) {
                serverChannel_accept.socket().close();
                serverChannel_accept.close();
                serverChannel_accept = null;
            }

        } catch (IOException e) {
            logger.info("close_all,error=",e);
            e.printStackTrace();
        }
        static_var.map_token.clear();
        static_var.map_machine.clear();
        static_var.map_socket.clear();
        static_var.map_history.clear();

        TaskService.ServerSocketChannel_init(SocketNIO.DEFAULT_PORT);
        MyComp.mo.excutVoidTask3();
        try{
            static_var.database_to_map();
        }
        catch(Exception e){
            logger.info("main,error=",e);
            e.printStackTrace();
        }
    }
    @Async


    public  void excutVoidTask111() {
        while (true) {
            try {
//                logger.info("excutVoidTask111,111111");
//                logger.info("excutVoidTask111,buf_machine.nHead_machine=" + buf_machine.nHead_machine);
//                logger.info("excutVoidTask111,buf_machine.nTail_machine=" + buf_machine.nTail_machine);


//                Thread.sleep(1);
                byte[] cmd = new byte[1460];

                if (Cbuffer_machine.buffer_get(cmd)) {
//                    logger.info("excutVoidTask111,111111");
//                    logger.info("excutVoidTask111,buf_machine.nHead_machine=" + buf_machine.nHead_machine);
//                    logger.info("excutVoidTask111,buf_machine.nTail_machine=" + buf_machine.nTail_machine);

//                        Cmd_fun.print_cmd(array_temp);
                    handle_cmd(cmd,Cmd_fun.ip_port);
                }
//


               /* for (int i = 0; i < 100; i++) {
                    if(static_var.buffer_2[i].isbUsed()){
                        DataInfo dataInfo = static_var.buffer_2[i].getDataInfo();
                        ByteBuffer buffer = dataInfo.getBuffer_data();
                        String ip_port = dataInfo.getIp_port_data();
                        static_var.buffer_2[i].setbUsed(false);
                        excutVoidTask_data222(buffer,ip_port);
                    }
                }*/


            } catch (Exception e) {
                logger.info("error,excutVoidTask111...=",e);
                e.printStackTrace();
            }

        }
    }

    public static void excutVoidTask_data222(ByteBuffer buffer,String ip_port) {
//        System.out.println("异步执行任务第[" + i + "] 个");
        byte[] array_temp = new byte[1460];
        byte[] aaa = new byte[buffer.limit()];
        if (!Cmd_fun.cmd_analysis_1(array_temp,buffer)) {
        }else{
//                        Cmd_fun.print_cmd(array_temp);
            handle_cmd(array_temp,ip_port);
        }

    }
    @Async
    public void excutVoidTask_data(ByteBuffer buffer,String ip_port) {
//        System.out.println("异步执行任务第[" + i + "] 个");
        byte[] array_temp = new byte[1460];
        byte[] aaa = new byte[buffer.limit()];
        if (!Cmd_fun.cmd_analysis_1(array_temp,buffer)) {
        }else{
//                        Cmd_fun.print_cmd(array_temp);
            handle_cmd(array_temp,ip_port);
        }

    }
    @Async
    public void excutVoidTask_data_push(String str_event_Q,String str_event_code_three,String str_machine,String str_number,String str_data_pure) {
//        System.out.println("异步执行任务第[" + i + "] 个");
        List<Token> list_token = static_var.map_token.get(str_machine);
        if (!((list_token == null) || list_token.isEmpty())) {
//            logger.info("list_token=" + list_token);
//            logger.info("list_token.size=" + list_token.size());
            for (int i = 0;i < list_token.size();i++) {
                String str_token = list_token.get(i).getToken_name();
                String str_language = list_token.get(i).getLanguage();
                String str_brand = list_token.get(i).getBrand();
                Integer length_token = list_token.get(i).getLength_token();
                Integer receipt = list_token.get(i).getReceipt();

                /*logger.info("str_token=" + str_token);
                logger.info("str_language=" + str_language);*/
                String str_event_chinese_or_english = Cmd_fun
                        .event_cid_tostring_event_code_chinese_or_english(str_event_Q,str_event_code_three,str_language);
//                logger.info("str_event_chinese_or_english=" + str_event_chinese_or_english);
                if (str_event_chinese_or_english.equals("") || str_event_chinese_or_english.length() <= 0) {
//                    logger.info("error,no this event,str_event_chinese_or_english=" + str_event_chinese_or_english);
                    return;
                }
                String str_content = "[" + str_machine + ":" + str_data_pure;
//                logger.info("str_content=" + str_content);
//                logger.info("str_brand=" + str_brand);
                if (str_brand.contains("Xiaomi")) {
                    str_token = str_token.substring(0,64);
//                    logger.info("str_token_xiaomi=" + str_token);
                    try {
                        xiaomi_push.sendMessageToAlias3(str_token,str_event_chinese_or_english,str_machine,str_number,str_data_pure);
//                        String alias2 = "1JC/eDRYxjPSYfI0l3heX8GhoBMcfGar8QXzEt6H0pqP6TX9ujw8WigknprWj+ZN";
//                        xiaomi_push.sendMessageToAlias2(alias2);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if(str_brand.contains("HONOR")){//HONOR
                    /*if (str_token.substring(32).equals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")) {
                        str_token = str_token.substring(0,32);
                    }else if (str_token.substring(114).equals("0000000000000000")) {
                        str_token = str_token.substring(0,114);
                        logger.info("str_token_honor115=" + str_token);
                    }

                    logger.info("str_token_honor=" + str_token);*/
//                    logger.info("length_token=" + length_token);
                    str_token = str_token.substring(0,length_token);
//                    logger.info("str_token_honor=" + str_token);


//                    PushNcMsg.sendPushMessage(str_token,str_alarm_event,str_machine,str_number,str_data_pure);
                    try {
                        static_var.push_huawei_obj.huawei_initialize_app();
                        static_var.push_huawei_obj.sendNotification2(str_token,str_event_chinese_or_english,"[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }


                }else if (str_brand.contains("Vivo")) {

//                    logger.info("str_content_vivo=" + "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english);
                    str_token = str_token.substring(0,23);
//                    logger.info("str_token_vivo=" + str_token);
                    try {
                        vivo_push.send_message_vivo_to_regid_offiial_edition(str_token,str_event_chinese_or_english,
                                "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("OPPO")) {
                    str_token = str_token.substring(0,35);
//                    logger.info("str_token_oppo=" + str_token);
                    try {
                        String regId = "CN_a813bde520a0cf430007a023f4850e0f";
                        oppo_push.send_message_oppo_to_regid(str_token,str_event_chinese_or_english,
                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("samsung")) {
                    try {
                        Messaging.send_message_fcm_to_regid(str_token,str_event_chinese_or_english,
                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }



            }
        }
        else{
            logger.info("error,str_machine=“ +　str_machine　”， is not exist" );
        }

    }

    public void excutVoidTask_data_push4(String str_event_Q,String str_event_code_three,String str_machine,String str_number,String str_data_pure,String str_event_chinese_or_english,String str_brand,final String str_token2,Integer length_token)  throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(2);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>()
        {
            @Override
            public Integer get() {
                logger.info("===task start===");
                //        System.out.println("异步执行任务第[" + i + "] 个");
                logger.info("str_brand=" + str_brand);
                String str_token = str_token2;
                static_var.nums_push++;
                /*logger.info("static_var.nums_push=" + static_var.nums_push + ",static_var.map_token.size=" + static_var.map_token.size()
                        + ",static_var.map_history.size=" + static_var.map_history.size());*/
                if (str_brand.contains("Xiaomi")) {

                    str_token = str_token.substring(0,64);
//                    logger.info("str_token_xiaomi=" + str_token);
                    try {
//                        xiaomi_push.sendMessageToAlias3(str_token,str_event_chinese_or_english,str_machine,str_number,str_data_pure);

                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if(str_brand.contains("HONOR")){//HONOR
                    /*if (str_token.substring(32).equals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")) {
                        str_token = str_token.substring(0,32);
                    }else if (str_token.substring(114).equals("0000000000000000")) {
                        str_token = str_token.substring(0,114);
                        logger.info("str_token_honor115=" + str_token);
                    }

                    logger.info("str_token_honor=" + str_token);*/
//                    logger.info("length_token=" + length_token);
                    str_token = str_token.substring(0,length_token);
//                    logger.info("str_token_honor=" + str_token);


//                    PushNcMsg.sendPushMessage(str_token,str_alarm_event,str_machine,str_number,str_data_pure);
                    try {
//                        static_var.push_huawei_obj.huawei_initialize_app();
//                        static_var.push_huawei_obj.sendNotification2(str_token,str_event_chinese_or_english,"[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }


                }else if (str_brand.contains("Vivo")) {

//                    logger.info("str_content_vivo=" + "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english);
                    str_token = str_token.substring(0,23);
//                    logger.info("str_token_vivo=" + str_token);
                    try {
//                        vivo_push.send_message_vivo_to_regid_offiial_edition(str_token,str_event_chinese_or_english,
//                                "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("OPPO")) {
                    str_token = str_token.substring(0,35);
                    String str_token2 ="OPPO_" + str_token;
//                    logger.info("str_token_oppo=" + str_token);
                    try {
                        String regId = "CN_a813bde520a0cf430007a023f4850e0f";
//                        oppo_push.send_message_oppo_to_regid(str_token2,str_event_chinese_or_english,
//                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("samsung")) {
                    try {
//                        logger.info("data_samsung=" + "[" + str_machine + ":" + str_data_pure);
                        Messaging.send_message_fcm_to_regid(str_token,str_event_chinese_or_english,
                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }


                System.out.println("===task finish===");
                return 3;
            }
        }, executor);
//        boolean cancel = future.cancel(true);
        executor.shutdown();
//        logger.info("===task finish2===" + "cancel=" + cancel);
        future.thenAccept(e -> logger.info("excutVoidTask_data_push4＝" +e));
    }

    @Async
    public Future<String> excutVoidTask_data_push3(String str_event_Q,String str_event_code_three,String str_machine,String str_number,String str_data_pure,String str_event_chinese_or_english,String str_brand,String str_token,Integer length_token)  throws InterruptedException{
        //        System.out.println("异步执行任务第[" + i + "] 个");
//                logger.info("str_brand=" + str_brand);
        static_var.nums_push++;
        logger.info("static_var.nums_push=" + static_var.nums_push);
        if (str_brand.contains("Xiaomi")) {
            str_token = str_token.substring(0,64);
//                    logger.info("str_token_xiaomi=" + str_token);
            try {
                xiaomi_push.sendMessageToAlias3(str_token,str_event_chinese_or_english,str_machine,str_number,str_data_pure);
//                        String alias2 = "1JC/eDRYxjPSYfI0l3heX8GhoBMcfGar8QXzEt6H0pqP6TX9ujw8WigknprWj+ZN";
//                        xiaomi_push.sendMessageToAlias2(alias2);
            } catch (Exception e) {
                logger.info("push_msg_for_machine_name,error=",e);
                e.printStackTrace();
            }
        }else if(str_brand.contains("HONOR")){//HONOR
                    /*if (str_token.substring(32).equals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")) {
                        str_token = str_token.substring(0,32);
                    }else if (str_token.substring(114).equals("0000000000000000")) {
                        str_token = str_token.substring(0,114);
                        logger.info("str_token_honor115=" + str_token);
                    }

                    logger.info("str_token_honor=" + str_token);*/
//                    logger.info("length_token=" + length_token);
            str_token = str_token.substring(0,length_token);
//                    logger.info("str_token_honor=" + str_token);


//                    PushNcMsg.sendPushMessage(str_token,str_alarm_event,str_machine,str_number,str_data_pure);
            try {
                static_var.push_huawei_obj.huawei_initialize_app();
                static_var.push_huawei_obj.sendNotification2(str_token,str_event_chinese_or_english,"[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
            } catch (Exception e) {
                logger.info("push_msg_for_machine_name,error=",e);
                e.printStackTrace();
            }


        }else if (str_brand.contains("Vivo")) {

//                    logger.info("str_content_vivo=" + "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english);
            str_token = str_token.substring(0,23);
//                    logger.info("str_token_vivo=" + str_token);
            try {
                vivo_push.send_message_vivo_to_regid_offiial_edition(str_token,str_event_chinese_or_english,
                        "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english,str_machine,str_data_pure);
            } catch (Exception e) {
                logger.info("push_msg_for_machine_name,error=",e);
                e.printStackTrace();
            }
        }else if (str_brand.contains("OPPO")) {
            str_token = str_token.substring(0,35);
//                    logger.info("str_token_oppo=" + str_token);
            try {
                String regId = "CN_a813bde520a0cf430007a023f4850e0f";
                oppo_push.send_message_oppo_to_regid(str_token,str_event_chinese_or_english,
                        "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
            } catch (Exception e) {
                logger.info("push_msg_for_machine_name,error=",e);
                e.printStackTrace();
            }
        }else if (str_brand.contains("samsung")) {
            try {
                Messaging.send_message_fcm_to_regid(str_token,str_event_chinese_or_english,
                        "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
            } catch (Exception e) {
                logger.info("push_msg_for_machine_name,error=",e);
                e.printStackTrace();
            }
        }
        return new AsyncResult<String>("任务4");
    }

    @Async
    public void excutVoidTask_data_push2(String str_event_Q,String str_event_code_three,String str_machine,String str_number,String str_data_pure,String str_event_chinese_or_english,String str_brand,String str_token,Integer length_token) {
//        System.out.println("异步执行任务第[" + i + "] 个");
//                logger.info("str_brand=" + str_brand);
                static_var.nums_push++;
                logger.info("static_var.nums_push=" + static_var.nums_push);
                if (str_brand.contains("Xiaomi")) {
                    str_token = str_token.substring(0,64);
//                    logger.info("str_token_xiaomi=" + str_token);
                    try {
                        xiaomi_push.sendMessageToAlias3(str_token,str_event_chinese_or_english,str_machine,str_number,str_data_pure);
//                        String alias2 = "1JC/eDRYxjPSYfI0l3heX8GhoBMcfGar8QXzEt6H0pqP6TX9ujw8WigknprWj+ZN";
//                        xiaomi_push.sendMessageToAlias2(alias2);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if(str_brand.contains("HONOR")){//HONOR
                    /*if (str_token.substring(32).equals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")) {
                        str_token = str_token.substring(0,32);
                    }else if (str_token.substring(114).equals("0000000000000000")) {
                        str_token = str_token.substring(0,114);
                        logger.info("str_token_honor115=" + str_token);
                    }

                    logger.info("str_token_honor=" + str_token);*/
//                    logger.info("length_token=" + length_token);
                    str_token = str_token.substring(0,length_token);
//                    logger.info("str_token_honor=" + str_token);


//                    PushNcMsg.sendPushMessage(str_token,str_alarm_event,str_machine,str_number,str_data_pure);
                    try {
                        static_var.push_huawei_obj.huawei_initialize_app();
                        static_var.push_huawei_obj.sendNotification2(str_token,str_event_chinese_or_english,"[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }


                }else if (str_brand.contains("Vivo")) {

//                    logger.info("str_content_vivo=" + "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english);
                    str_token = str_token.substring(0,23);
//                    logger.info("str_token_vivo=" + str_token);
                    try {
                        vivo_push.send_message_vivo_to_regid_offiial_edition(str_token,str_event_chinese_or_english,
                                "#" + str_machine + ":" + str_data_pure.substring(0,str_data_pure.length() - 1) + str_event_chinese_or_english,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("OPPO")) {
                    str_token = str_token.substring(0,35);
//                    logger.info("str_token_oppo=" + str_token);
                    try {
                        String regId = "CN_a813bde520a0cf430007a023f4850e0f";
                        oppo_push.send_message_oppo_to_regid(str_token,str_event_chinese_or_english,
                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }else if (str_brand.contains("samsung")) {
                    try {
                        Messaging.send_message_fcm_to_regid(str_token,str_event_chinese_or_english,
                                "[" + str_machine + ":" + str_data_pure,str_machine,str_data_pure);
                    } catch (Exception e) {
                        logger.info("push_msg_for_machine_name,error=",e);
                        e.printStackTrace();
                    }
                }




    }

    @Async
    public Future<String> excuteValueTask(int i) throws InterruptedException {
        Thread.sleep(1000);
        Future<String> future = new AsyncResult<String>("success is " + i);
        System.out.println("异步执行任务第[" + i + "] 个");
        return future;
    }

    @Async

    public void excutVoidTask2() {

        boolean flag_temp = true;
        int nums = 0;
        while (flag_temp) {
            try {
                Thread.sleep(1000);

                long time_now = System.currentTimeMillis();
                /*long time_temp = time_now - static_var.time_recv;
                logger.info("excutVoidTask2...,time_temp=" + time_temp);
                if (time_temp > 40000) {
                    logger.info("error,excutVoidTask2...,time_temp=" + time_temp);
                    static_var.time_recv = System.currentTimeMillis();
                    close_all();
                }*/
                nums++;
                logger.info("excutVoidTask2...,nums=" + nums);
                if (nums > 18) {
                    nums = 0;

                    close_all();
//                    flag_temp = false;
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
    @Async

    public void excutVoidTask3() {
        while (started) {
            try {
                Thread.sleep(10);
//                logger.info("excutVoidTask3...");
                if ((serverChannel_accept.isOpen()) && (selector.isOpen()) && (selector != null)) {
//                    logger.info("excutVoidTask3,111");
                    int num = selector.select();
                    if(num<1){
                        continue;
                    }
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> it = keys.iterator();
                    boolean flag = keys.isEmpty();
                    int size = keys.size();
//                    logger.info("excutVoidTask3,size=" + size);
                    if (size > 0) {
                        if (!flag) {
                            for(SelectionKey name:keys){
                                if (name == null) {
                                    logger.info("error,excutVoidTask3,name is null");
                                    return;
                                }
                                handleInput(name);
                            }
                            keys.clear();
                        }
                    }
                }
            } catch (Exception e) {
                logger.info("run,error=",e);
                e.printStackTrace();
            }

        }
    }


    private static void stop(){
        started = false;
    }

    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            //处理新接入的请求消息
//            logger.info("handleInput,222");

            if(key.isAcceptable()){
                try {
                    if ((serverChannel_accept.isOpen()))
                    {
                        logger.info("handleInput,333");
                        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                        //通过ServerSocketChannel的accept创建SocketChannel实例
                        //完成该操作意味着完成TCP三次握手，TCP物理链路正式建立
                        SocketChannel socketChannel_data = ssc.accept();
                        //设置为非阻塞的
                        socketChannel_data.configureBlocking(false);
                        socketChannel_data.setOption(StandardSocketOptions.SO_KEEPALIVE,true);
                        //注册为读
                        socketChannel_data.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocateDirect(1024));
                        //                udp_cmd.socket_temp = sc;
                        String ip = socketChannel_data.socket().getInetAddress().toString();
                        if (ip.contains("/")) {
                            ip = ip.substring(1);
                        }
                        if (!ip.equals("43.130.3.36")) {
                            logger.info("isAcceptable,ip=" + ip);
                            return;
                        }
                        String ip_port = get_ip_prot(socketChannel_data);
                        logger.info("handleInput,ip_port=" + ip_port);
                        static_var.map_socket.clear();
                        static_var.map_socket.put(ip_port,socketChannel_data);
                        /*if (!static_var.map_socket.containsKey(ip_port)) {
                            static_var.map_socket.put(ip_port,socketChannel_data);
                        }else{
                            static_var.map_socket.remove(ip_port);
                            static_var.map_socket.put(ip_port,socketChannel_data);
                        }*/
                    }


                } catch (Exception e) {
                    logger.info("handleInput,isAcceptable,error=",e);
                    e.printStackTrace();
                }

            }

            //读消息
            if(key.isReadable()){
//                logger.info("handleInput,444");
                try{
                    if ((serverChannel_accept.isOpen()))
                    {
                        /*logger.info("serverChannel_accept.isOpen()=" + serverChannel_accept.isOpen());
                        logger.info("key.isConnectable()=" + key.isConnectable());
                        logger.info("socketChannel_data.finishConnect()=" + socketChannel_data.finishConnect());
                        logger.info("socketChannel_data.isConnected()=" + socketChannel_data.isConnected());
                        logger.info("handleInput,555");*/
                        SocketChannel socketChannel_data_temp = (SocketChannel) key.channel();

                        String ip = socketChannel_data_temp.socket().getInetAddress().toString();
                        if (ip.contains("/")) {
                            ip = ip.substring(1);
                        }
//                        logger.info("isReadable,ip=" + ip);
                        String ip_port = get_ip_prot(socketChannel_data_temp);
                        if (!ip.equals("43.130.3.36")) {
                            logger.info("isReadable,ip=" + ip);
                            return;
                        }

                        ByteBuffer buffer = ByteBuffer.allocate(4096);
                        buffer.clear();
                        int readBytes = socketChannel_data_temp.read(buffer);
                        if(readBytes>0){
                            buffer.flip();
                            excutVoidTask_data(buffer,ip_port);
                        }
                    }

                }
                catch(Exception e){
                    logger.info("handleInput,isReadable,error=",e);
                    e.printStackTrace();
                }

            }
        }
    }

    public static void handle_cmd(byte[] cmd,String ip_port) {
        try{
            boolean bflag_crc_check_std = Cmd_fun.crc_check_std(cmd,0);
            if(bflag_crc_check_std){
                boolean bflag_crc_check_pri = Cmd_fun.crc_check_pri(cmd,0);
                if(bflag_crc_check_pri){
                    command_handle(cmd,ip_port);
                }else{

                    logger.info("Thread_1 1,error cmd................................");
                }
            }else{

                logger.info("Thread_1 2,error cmd................................");
            }
        }
        catch(Exception e){
            logger.info("handle_cmd,error=",e);
            e.printStackTrace();
        }

    }

    private static void command_handle(byte[] cmd,String ip_port)
    {
//
        try {
            SpringJdbcTemplate springJdbcTemplate = new SpringJdbcTemplate();
            byte[] buf_len = new byte[5];
            for (int i = 0; i < 5; i++) {
                buf_len[i] = 0;
            }
            int len_std_a = 0;
            int len_std_b = 0;
            if (cmd[7] < 58) {
                len_std_a = cmd[7] - 48;
            } else if ((cmd[7] >= 65) && (cmd[7] <= 70)) {
                len_std_a = cmd[7] - 55;
            }
            if (cmd[8] < 58) {
                len_std_b = cmd[8] - 48;
            } else if ((cmd[8] >= 65) && (cmd[7] <= 70)) {
                len_std_b = cmd[8] - 55;
            }
            int len_standard = len_std_a * 16 + len_std_b;
//            logger.info("len_standard=" + len_standard);
            int len_pri = cmd[len_standard + 10] * 256
                    + (int) (cmd[len_standard + 10 + 1] & 0xff);
//            logger.info("len_pri=" + len_pri);
            int len_total = len_standard + len_pri + 10 + 2 + 4;
//            logger.info("len_total=" + len_total);
//            logger.info("www=" + len_standard + " " + len_pri + " " + len_total);
            int len_temp = len_standard + 31 + 10;
            // ////////////////////////////////////////////////////////////////////////////////

            int big_class = cmd[len_temp];
            int small_class = cmd[len_temp + 1];
//            Cmd_fun.print_cmd(cmd);

            long conn_number = (((byte)(cmd[len_temp + 2]) & 0xff)) * 65536 + (((byte)(cmd[len_temp + 3]) & 0xff))
                    * 256 + (((byte)(cmd[len_temp + 4]) & 0xff));



            if (big_class == 0x33)
            {
                if (small_class == 00)
                {
                    static_var.time_recv = System.currentTimeMillis();
                    logger.info("big_class=0x" + Cmd_fun.bytesToHexString((byte) big_class) + " small_class=0x" + Cmd_fun.bytesToHexString((byte) small_class) + ":" + ip_port);
                    Cmd_fun.send_44_00(0,ip_port);
//                    logger.info("static_var.map_socket=" + static_var.map_socket);
                }
            }
            else if (big_class == 0x00)
            {
                static_var.time_recv = System.currentTimeMillis();
                if (small_class == 0x03)
                {
//                    Cmd_fun.print_cmd(cmd);
                    byte[] buf_acct_machine = new byte[9];
                    System.arraycopy(cmd, len_standard + 12, buf_acct_machine, 0,
                            buf_acct_machine.length);
                    String str_acct_machine = Cmd_fun.HexByteToNumString(
                            buf_acct_machine, (byte) buf_acct_machine.length);
//                    logger.info("str_acct_machine=" + str_acct_machine);


                    ///////////////////////////////////////////////////////////////////////////////////
                    int length_token = (int)(cmd[len_temp + 5 + 163] & 0xff);
//                    logger.info("length_token=" + length_token);
                    if (length_token < 4) {
                        return;
                    }

                    byte[] buf_device_token = new byte[163];
                    for(int i = 0; i < buf_device_token.length; i++)
                    {
                        buf_device_token[i] = 0;
                    }
                    System.arraycopy(cmd, len_temp + 5, buf_device_token, 0,buf_device_token.length);
                    String str_device_token = new String(buf_device_token);
//                    logger.info("str_device_token=" + str_device_token);
                    if (str_device_token.length() < 163) {
                        return;
                    }
                    static_var.str_device_token = str_device_token;
                    String str_left_4 = static_var.str_device_token.substring(0,4);
                    if (static_var.str_device_token.equals("null000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
                            || static_var.str_device_token.equals("null000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
                            || str_left_4.equals("null")) {
                        return;
                    }
                    if (!(static_var.str_device_token.equals("")
                            || static_var.str_device_token.length() <= 0
                            || static_var.str_device_token.equals(null)))
                    {
                        byte[] buf_temp = new byte[7];
                        for (int i = 0; i < 7; i++) {
                            buf_temp[i] = 0;
                        }
                        System.arraycopy(cmd,len_temp - 7,buf_temp,0,7);
//                        Cmd_fun.print_cmd_hex(buf_temp,7);


                        int i_temp = (byte) (buf_temp[1] & 0xff);
                        int i_machine_type2 = ((i_temp >> 4) &  0x0f);
//                        logger.info("i_machine_type2=" + String.valueOf(i_machine_type2));
                        springJdbcTemplate.machine_insert(str_acct_machine,i_machine_type2,"无","无");
                        //////////////////////////////////////////////////////////////////////////////////////////
//                        logger.info("aaa1");
                        String str_language = "China";
                        Integer i_language = (int) ((buf_temp[4] >> 4) & 0x0f);
//                        logger.info("ddnot,i_language=" + i_language);
                        if (i_language == 0) {
                            str_language = "China";
                        }else if (i_language == 1){
                            str_language = "English";
                        }else if (i_language == 2){
                            str_language = "German";
                        }else if (i_language == 3){
                            str_language = "Russian";
                        }else if (i_language == 4){
                            str_language = "French";
                        }else if (i_language == 5){
                            str_language = "Italian";
                        }else if (i_language == 6){
                            str_language = "Spanish";
                        }else if (i_language == 7){
                            str_language = "Portuguese";
                        }else if (i_language == 8){
                            str_language = "Arabic";
                        }
                        String str_brand = "HONOR";
                        Integer i_brand = (int) ((buf_temp[4]) & 0x0f);
//                        logger.info("ddnot,i_brand=" + i_brand);
                        if (i_brand == 0) {
                            str_brand = "HONOR";
                        }else if (i_brand == 1){
                            str_brand = "Xiaomi";
                        }else if (i_brand == 2){
                            str_brand = "OPPO";
                            String str1 = "";
                            String str2 = "";

                            String str_left_44 = static_var.str_device_token.substring(0,5);
                            if (str_left_44.equals("OPPO_")) {
                                str1 = static_var.str_device_token.substring(5,static_var.str_device_token.length());
                                static_var.str_device_token = str1 + "00000";
//                                return;
                            }
                        }else if (i_brand == 3){
                            str_brand = "Vivo";
                        }else if (i_brand == 4){
                            str_brand = "samsung";
                        }
//                        logger.info("ddnot,str_language=" + str_language);
//                        logger.info("ddnot,str_brand=" + str_brand);

//                        springJdbcTemplate.token_insert(static_var.str_device_token,str_language,str_brand,str_acct_machine);
                        int receipt = 0;
                        springJdbcTemplate.token_insert_according_to_machine_id(static_var.str_device_token,str_language,str_brand,str_acct_machine,length_token,receipt);

                        static_var.write_data_into_map(str_acct_machine,str_language,str_brand,str_device_token,length_token,receipt);


                        String str_alarm_events[] = new String[1];
                        Integer nums [] = new Integer[1];

                        static_var.get_alarm_event_from_map_history(str_acct_machine,str_alarm_events,nums);


//                        logger.info("ddnot,str_alarm_events[0]=" + str_alarm_events[0]);
                        if ((nums[0] > 0) && (nums[0] < 21)) {
//                            if (str_acct_machine.equals("866569060902449")) {
//                                logger.info("ddnot,nums[0]=" + nums[0] + ",str_acct_machine=" + str_acct_machine);
////                                Cmd_fun.print_cmd(cmd);
//                            }

                            Cmd_fun.send_44_04(conn_number,ip_port,str_acct_machine);
                        }



                    }
                }
                else if (small_class == 0x04)
                {

                    logger.info("big_class=0x" + Cmd_fun.bytesToHexString((byte) big_class) +
                            " small_class=0x" + Cmd_fun.bytesToHexString((byte) small_class) +
                            ":" + ip_port);
                    byte[] buf_acct_machine = new byte[9];
                    System.arraycopy(cmd, len_standard + 12, buf_acct_machine, 0,
                            buf_acct_machine.length);
                    String str_acct_machine = Cmd_fun.HexByteToNumString(
                            buf_acct_machine, (byte) buf_acct_machine.length);
                    logger.info("str_acct_machine=" + str_acct_machine);


                    ///////////////////////////////////////////////////////////////////////////////////
                    int length_token = (int)(cmd[len_temp + 5 + 163] & 0xff);
                    logger.info("length_token=" + length_token);


                    byte[] buf_device_token = new byte[163];
                    for(int i = 0; i < buf_device_token.length; i++)
                    {
                        buf_device_token[i] = 0;
                    }
                    System.arraycopy(cmd, len_temp + 5, buf_device_token, 0,buf_device_token.length);
                    String str_device_token = new String(buf_device_token);
//                    logger.info("str_device_token=" + str_device_token);
                    if (str_device_token.length() < 163) {
                        return;
                    }
                    static_var.str_device_token = str_device_token;
                    String str_left_4 = static_var.str_device_token.substring(0,4);
                    if (static_var.str_device_token.equals("null000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
                            || static_var.str_device_token.equals("null000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
                            || str_left_4.equals("null")) {
                        return;
                    }
                    if (!(static_var.str_device_token.equals("")
                            || static_var.str_device_token.length() <= 0
                            || static_var.str_device_token.equals(null)))
                    {
                        logger.info("command_handle,str_device_token=" + str_device_token);
                        springJdbcTemplate.token_delete(str_device_token);
                        static_var.remove_token_according_to_machine_name(str_acct_machine,str_device_token);
                        Cmd_fun.send_44_01(conn_number,ip_port,1);
                    }

                }
            }else if (big_class == 0x05) {
                if (small_class == 00) {
//                    Cmd_fun.print_cmd(cmd);
                    static_var.time_recv = System.currentTimeMillis();
                    byte[] buf_acct_machine = new byte[9];
                    System.arraycopy(cmd, len_standard + 12, buf_acct_machine, 0,
                            buf_acct_machine.length);
                    String str_acct_machine = Cmd_fun.HexByteToNumString(
                            buf_acct_machine, (byte) buf_acct_machine.length);

                    String[] str_event_alarm_temp = new String[6];
                    Cmd_fun.event_cid_tostring_event_code_complete(cmd,
                            str_event_alarm_temp);
                    String str_event_code_three = str_event_alarm_temp[0];
                    String str_zone_number_final = str_event_alarm_temp[1];
                    String str_event_Q = str_event_alarm_temp[2];
                    String str_data_pure = str_event_alarm_temp[3];
                    String str_time_alarm_event = str_event_alarm_temp[4];
                    String str_all_pure_data = str_event_alarm_temp[5];



                    if (str_acct_machine.equals("20105135248212")) {
//                        Cmd_fun.print_cmd(cmd);
                        logger.info("05 00.............str_acct_machine=" + str_acct_machine);
                        logger.info("05 00.............str_event_code_three=" + str_event_code_three);
                        logger.info("05 00.............str_zone_number_final=" + str_zone_number_final);
                        logger.info("05 00.............str_data_pure=" + str_data_pure);
                        logger.info("05 00.............str_time_alarm_event=" + str_time_alarm_event);
                        logger.info("05 00.............str_all_pure_data=" + str_all_pure_data);
                    }

                    if (str_acct_machine.equals("866569060902449")) {
//                        Cmd_fun.print_cmd(cmd);
                        logger.info("05 00.............str_acct_machine=" + str_acct_machine);
                        logger.info("05 00.............str_event_code_three=" + str_event_code_three);
                        logger.info("05 00.............str_zone_number_final=" + str_zone_number_final);
                        logger.info("05 00.............str_data_pure=" + str_data_pure);
                        logger.info("05 00.............str_time_alarm_event=" + str_time_alarm_event);
                        logger.info("05 00.............str_all_pure_data=" + str_all_pure_data);
                    }

                    ////////////////////////////////////////////////////////////////////////////////
//                    static_var.str_device_token
//                    PushNcMsg.sendPushMessage(static_var.str_device_token,str_event_alarm,str_acct_machine,str_zone_number_final,str_data_pure);
                    if (str_acct_machine.equals("") || str_acct_machine.length() <= 0) {
                        logger.info("error,05 00.............str_acct_machine is empty");
                        return;
                    }
                    if (str_event_code_three.equals("") || str_event_code_three.length() <= 0) {
                        logger.info("error,05 00.............str_event_code_three is empty");
                        return;
                    }
                    if (str_zone_number_final.equals("") || str_zone_number_final.length() <= 0) {
                        logger.info("error,05 00.............str_zone_number_final is empty");
                        return;
                    }
                    if (str_data_pure.equals("") || str_data_pure.length() <= 0) {
                        logger.info("error,05 00.............str_data_pure is empty");
                        return;
                    }

                    static_var.insert_alarm_event_into_map_history(str_acct_machine,str_all_pure_data,str_time_alarm_event);

//                    logger.info("05 00.............str_data_pure=" + str_data_pure);
                    static_var.push_msg_for_machine_name(str_event_Q,str_event_code_three,str_acct_machine,str_zone_number_final,str_data_pure);
//                    MyComp.mo.excutVoidTask_data_push(str_event_Q,str_event_code_three,str_acct_machine,str_zone_number_final,str_data_pure);

                    //                    String alias2 = "1JC/eDRYxjPSYfI0l3heX8GhoBMcfGar8QXzEt6H0pqP6TX9ujw8WigknprWj+ZN";
//                    xiaomi_push.sendMessageToAlias2(alias2);
                    /*String str_alarm_events[] = new String[1];
                    static_var.get_alarm_event_from_map_history("868626044227521",str_alarm_events);
                    logger.info("str_alarm_events[0]=" + str_alarm_events[0]);*/
                }
            }

        }catch (Exception e) {
            Log.e("command_handle=" + e.toString());
            // TODO Auto-generated catch block
            logger.info("command_handle,,,,,,,,,,,,,exception error " + e.toString());
        }
    }

    public static String  get_ip_prot(SocketChannel sc) {
        String str_ip = sc.socket().getInetAddress().toString();
        if (str_ip.contains("/")) {
            str_ip = str_ip.substring(1);
        }
        Integer port = sc.socket().getPort();
        String ip_prot = str_ip + ":" + port;
//        logger.info("str_ip=" + str_ip);
//        logger.info("port=" + port);/
//        logger.info("ip_prot=" + ip_prot);
        return ip_prot;
    }
}
